<?php

namespace app\api\controller\shop;


use app\admin\model\shop\Commission;
use app\admin\model\shop\Withdraw;
use app\admin\model\Shoproom;
use app\admin\model\Shopstaff;
use app\admin\model\Useragent;
use app\admin\model\Usercard;
use app\admin\model\Userwithdraw;
use app\api\service\BalanceService;
use app\api\service\BankService;
use app\api\service\CommonService;
use app\common\controller\Api;
use app\api\controller\shop;

/**
 *
 */
class Money extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function configInit(BalanceService $balanceService)
    {
        $ret = array();
        $role = $this->request->param('role');
        $shopId = $this->request->param('shopId');
        //1. 是否实名
        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id', $user['id'])->find();
        if ($user['idcard'] == '') {
            $this->error("", "", -2);
        }
        $ret['username'] = $user['username'];

        //2. 是否添加银行卡
        $userCardModel = new Usercard();
        $userCard = $userCardModel->where('user_id', $user['id'])->find();
        if ($userCard == null) {
            $this->error("", $ret, -3);
        }
        $shopModel = new \app\admin\model\Shop();
        if ($shopId) {
            $shop = $shopModel->where('id', $shopId)->find();
            if ($shop['is_profile'] == -1) {
                $this->error("", '', -4);
            }
        }

        $ret['needCommission'] = false;
        $ret['commission_amount'] = 0;
        $ret['card'] = $userCard;
        if ($role == '商家') {
            //查询用户所属店铺是否符合O抽佣,
            $shops = $shopModel->where('user_id', $user['id'])->select();
            $amountArr = [];
            foreach ($shops as $shop) {
                $shopCommissionSet = new Commission();
                $shopCommission = $shopCommissionSet->where('shop_id', $shop['id'])->where('start_date', '<=', time())->select();
                if (!empty($shopCommission)) {
                    $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00', time()));
                    $shopWitdrawModel = new Withdraw();
                    $list = $shopWitdrawModel->where('shop_id', $shop['id'])->where('type', 1)->where('createtime', '>=', $firstDayOfMonth)->find();
                    if (empty($list)) {
                        //计算该店铺需要抽佣的金额
                        $minAmount = $this->getShopMinMoney($shop['id']);
                        $amountArr[] = $minAmount;
                    }

                }
            }

            $ret['commission_amount'] = array_sum($amountArr);
            if ($ret['commission_amount'] > 0) {
                $ret['needCommission'] = true;
            }

            $balance = $balanceService->shopBalance($user['id']);

        } else if ($role == '代理商') {
            $balance = $balanceService->agentBalance($user['id']);
        } else if ($role == '助教') {
            $balance = $balanceService->assBalance($user['id']);
        } else {
            $balance = 0;
        }
        $ret['balance'] = $balance;
        $this->success('', $ret);
    }

    /**
     * 实名
     */
    public function verify(CommonService $commonService)
    {

        $username = $this->request->param('name');
        $idcard = $this->request->param('idcard');

        $userModel = new \app\admin\model\User();
//        $user = $userModel->where('idcard',$idcard)->find();
//        if($user){
//            $this->error("此身份证已实名过");
//        }
        $ret = $commonService->verify($idcard, $username);
        $obj = json_decode($ret, true);
        $status = $obj['status'];
        $msg = $obj['msg'];
        $user = $this->auth->getUser();
        if ($status == '01') {//通过
            $userModel->where('id', $user['id'])->update(['username' => $username, 'idcard' => $idcard]);
            $this->success('');
        } else {
            $this->error($msg);
        }

    }

    public function addBank()
    {

        $bankNum = $this->request->param('bankCard');
        $bankPhone = $this->request->param('bankPhone');


        $bankNum = str_replace(' ', '', $bankNum);
        $bankService = new BankService();
        $ret = $bankService->checkBank($bankNum);
        $data = json_decode($ret, true);
        $stat = $data['stat'];
        $bankName = "";
        $bankCode = "";

        if ($stat == 'ok') {
            $validated = $data['validated'];
            if (!$validated) {
                $this->error("卡号校验错误,请检查一遍");
            }
            $bankCode = $data['bank'];
            $bankName = json_decode($bankService->banks, true)[$bankCode];
        } else {
            $this->error("卡号错误,请检查一遍");

        }

        $uid = $this->auth->getUser()['id'];
        $user = $this->auth->getUser();
        $insertData = array();
        $insertData['user_id'] = $uid;
        $insertData['bank_name'] = $bankName;
        $insertData['bank_code'] = $bankCode;
        $insertData['bank_icon'] = "https://yangfubing.gitee.io/bank.logo/resource/logo/" . $bankCode . ".png";
        $insertData['card_num'] = $bankNum;
        $insertData['bank_phone'] = $bankPhone;
        $insertData['user_name'] = $user['username'];

        $userCardModel = new Usercard();
        $bank = $userCardModel->where('user_id', $uid)->find();
        if ($bank) {
            $userCardModel->where('id', $bank['id'])->update($insertData);
        } else {
            $userCardModel->insert($insertData);
        }
        $this->success('成功');
    }

    /**
     * 提现
     */
    public function doShopWithDraw(BalanceService $balanceService)
    {
        $db = array();
        $amount = $this->request->param('amount');
        $commission_amount = $this->request->param('commission_amount');//获取抽佣金额
        $role = $this->request->param('role');
        $user = $this->auth->getUser();
        $userWithDrawModel = new Userwithdraw();

        $fee = 0;
        $shop = '';
        if ($role == '商家') {
            $balance = $balanceService->shopBalance($user['id']);
            $db['type'] = 'shop';

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('user_id', $user['id'])->find();

            $todayCount = $userWithDrawModel->where('user_id', $user['id'])->whereTime("create_time", 'today')->count('id');
            if ($shop['org_id'] == 27) {

                if ($todayCount >= 1) {
                    $this->error("当天只能提现一次");
                }
                if ($amount < 100) {
                    $this->error("单笔必须要大于100");
                }

                if ($amount > 10000) {
                    $this->error("单笔不能超过1W");
                }
                $startToday = strtotime(date("Y-m-d") . " 09:30:00");
                $endToday = strtotime(date("Y-m-d") . " 16:00:00");
                if (time() < $startToday || time() > $endToday) {
                    $this->error("不在提现时间段09:30 ~ 16:00");
                }
            }

        } else if ($role == '代理商') {
            $db['type'] = 'user';
            $balance = $balanceService->agentBalance($user['id']);
        } else if ($role == '助教') {
            $balance = $balanceService->assEnableBalance($user['id']);
            $db['type'] = 'assistant';

        } else {
            $balance = 0;

        }
        if ($balance < $amount) {
            $this->error("余额不足");
        }

        $url = "http://vip.bitefu.net/jiari/?d=" . date('Ymd') . "&apikey=1eae257e44aa9d5b";
        $res = file_get_contents($url);    //json格式，前端需要直接提供
        $res = json_decode($res, true);
        $key = $res['data'];
        if ($key != 0) {
            $this->error("节假日或者周末不可提现");
        }

        $userCardModel = new Usercard();
        $card = $userCardModel->where('user_id', $user['id'])->find();

        $db['user_id'] = $user['id'];
        $db['user_name'] = $card['user_name'];
        $db['bank_num'] = $card['card_num'];
        $db['amount'] = $amount;
        $db['back_amount'] = $amount - $fee;

        //判断是否需要扣除抽佣款
        if ($commission_amount > 0) {
            $db['amount'] = formatMoney($amount - $commission_amount);
            $db['back_amount'] = formatMoney($amount - $fee - $commission_amount);
        }

        $db['create_time'] = time();
        $db['status'] = 'doing';

        $userWithDrawModel->insert($db);

        //判断是否存在抽佣金额，存在则扣除当月佣金
        if ($commission_amount > 0) {

            //查询抽佣的相关参数
            $shopCommissionModel = new Commission();
            $shopCommInfo = $shopCommissionModel->where('shop_id', $shop['id'])->find();
            if ($shopCommInfo['is_open'] == '-1') {
                //变更抽佣设置表的开启状态
                $shopCommissionModel->where('shop_id', $shop['id'])->update(['is_open' => 1]);

                //变更店铺对应的抽佣方式
                $shopModel = new \app\admin\model\Shop();
                $shopModel->where('id', $shop['id'])->update(['ratio' => 0.00, 'profit_type' => 1, 'is_all' => -1]);
            }

            //写入抽佣提现
            $newDb['user_id'] = $user['id'];
            $newDb['user_name'] = '用户操作提现';
            $newDb['type'] = 'shop';
            $newDb['bank_num'] = '扣除店铺当月平台服务费';
            $newDb['amount'] = $commission_amount;
            $newDb['back_amount'] = $commission_amount;
            $newDb['create_time'] = time();
            $newDb['status'] = 'success';

            $userWithDrawModel->insert($newDb);

            //写入系统店铺抽佣记录
            $nowMonth = date('Y年m月', time());
            $shopWitdrawModel = new Withdraw();
            $lastDb['user_id'] = $user['id'];
            $lastDb['shop_id'] = $shop['id'];
            $lastDb['type'] = 1;
            $lastDb['amount'] = $commission_amount;
            $lastDb['remark'] = $nowMonth . ' 店铺抽佣';
            $lastDb['createtime'] = time();

            $shopWitdrawModel->insert($lastDb);

        }

        $this->success('成功');

    }


    public function withDrawList()
    {

        $user = $this->auth->getUser();
        $page = $this->request->param("page");
        $type = $this->request->param('type');
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $userWithDrawModel = new Userwithdraw();
        $total = $userWithDrawModel->where('type', $type)->where('user_id', $user['id'])->sum('amount');

        $list = $userWithDrawModel->where('type', $type)->where('user_id', $user['id'])->order('create_time', 'desc')->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {
            if ($val['status'] == 'doing') {
                $list[$key]['status'] = '处理中';
            } else if (($val['status'] == 'success')) {
                $list[$key]['status'] = '处理成功';
            }
            $list[$key]['create_time_txt'] = date('Y-m-d', $val['create_time']);
        }
        $ret = array();
        $ret['total'] = $total;
        $ret['list'] = $list;


        $this->success('', $ret);

    }

    protected function getShopMinMoney($shop_id)
    {
        $shopRoomModel = new Shoproom();
        //查询店铺包厢数量
        $shopRoom = $shopRoomModel->where('shop_id', $shop_id)->count();
        //查询台桌数量
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopTable = $shopTableModel->where('shop_id', $shop_id)->count();
        $total = $shopRoom + $shopTable;

        //查询抽佣的相关参数
        $shopCommissionModel = new Commission();
        $shopCommInfo = $shopCommissionModel->where('shop_id', $shop_id)->find();
        $totalMoney = 0;
        if ($shopCommInfo && $shopCommInfo['start_date'] <= time()) {//判断抽佣开始日期，是否可以抽佣
            if ($total <= 7) {//数量少于7台则扣除599，大于7台，每增加1台多扣除85元/月
                $totalMoney = $shopCommInfo['min_amount'];
            } else {
                $totalMoney = $shopCommInfo['min_amount'] + ($total - 7) * $shopCommInfo['single_amount'];
            }
        }

        return $totalMoney;
    }

}
